<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="container">
          <el-form
            inline
            size="small"
            :model="from"
            ref="from"
            :label-position="labelPosition"
            label-width="100px"
          >
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="10" :xl="10">
                <el-form-item label="搜索关键字：">
                  <el-input
                    v-model="from.emailTemplateName"
                    placeholder="请输入邮件模板名称"
                    clearable
                    class="selWidth"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="24" :md="24" :lg="10" :xl="10">
                <el-form-item>
                  <el-button
                    class="mr10"
                    size="small"
                    type="primary"
                    @click="search()"
                    ><i class="el-icon-search mar6"></i>搜索</el-button
                  >
                  <el-button class="mr10" size="small" @click="reset()"
                    ><i class="el-icon-refresh mar6"></i>重置</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="btn_bt">
          <el-button class="mr10" size="small" type="primary" @click="add()"
            ><i class="el-icon-circle-plus-outline mar6"></i>添加</el-button
          >
          <el-button
            class="mr10"
            size="small"
            type="danger"
            @click="deleteCountry()"
            ><i class="el-icon-delete mar6"></i>删除</el-button
          >
        </div>
      </div>
      <el-table
        border
        ref="table"
        v-loading="loading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        highlight-current-row
        @select="selctTable"
        @select-all="slectTableAll"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="countryId" label="国家" min-width="90" />
        <el-table-column prop="emailContent" label="邮件内容" min-width="100" />
        <el-table-column
          prop="emailSender"
          label="邮件发件人名称"
          min-width="150"
        />
        <el-table-column
          prop="emailSenderAddress"
          label="邮件发件人地址"
          min-width="150"
        />
        <el-table-column prop="emailSubject" label="邮件主题" min-width="150" />
        <el-table-column
          prop="emailTemplateName"
          label="模板名称"
          min-width="150"
        />
        <el-table-column
          prop="emailTemplateNo"
          label="模板编号"
          min-width="150"
        />
        <el-table-column
          prop="emailTemplateType"
          label="模板类型"
          min-width="80"
        >
          <template slot-scope="scoped">
            <span v-if="scoped.row.emailTemplateType == 1">注册</span>
            <span v-if="scoped.row.emailTemplateType == 2">重置密码</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="描述" min-width="150" />
        <el-table-column prop="status" label="状态" min-width="80">
          <template slot-scope="scoped">
            <span v-if="scoped.row.status == 1">正常</span>
            <span v-if="scoped.row.status == 2">停用</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="150" />
        <el-table-column prop="updateTime" label="更新时间" min-width="150" />

        <el-table-column
          label="操作"
          min-width="80"
          fixed="right"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[15, 30, 45, 60]"
          :page-size="from.limit"
          :current-page="from.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <el-dialog
      :title="countryShow == 1 ? '新增邮件' : '修改邮件'"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="dialogEmail"
      top="5vh"
    >
      <el-form
        :rules="rules"
        ref="ruleForm"
        :model="ruleForm"
        label-width="120px"
      >
        <el-form-item label="国家:" prop="countryId">
          <!-- <el-input v-model="ruleForm.countryId" placeholder="请输入国家"></el-input> -->

          <UserSearchable v-model="ruleForm.countryId" :type="'getCountry'">
            <template #dropdownTitle>
              <span>国家主键</span>
              <span>国家名称</span>
              <span>国家英文名</span>
            </template>
            <template v-slot:dropdown="{ item }">
              <span>{{ item.countryId }}</span>
              <span>{{ item.countryName }}</span>
              <span>{{ item.countryEnglishName }}</span>
            </template>
          </UserSearchable>
        </el-form-item>
        <el-form-item label="模板名称:" prop="emailTemplateName">
          <el-input
            v-model="ruleForm.emailTemplateName"
            placeholder="模板名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="模板编号:" prop="emailTemplateNo">
          <el-input
            v-model="ruleForm.emailTemplateNo"
            placeholder="模板编号"
          ></el-input>
        </el-form-item>

        <el-form-item label="发件人名称:" prop="emailSender">
          <el-input
            v-model="ruleForm.emailSender"
            placeholder="邮件发件人名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="发件人地址:" prop="emailSenderAddress">
          <el-input
            v-model="ruleForm.emailSenderAddress"
            placeholder="邮件发件人地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="主题:" prop="emailSubject">
          <el-input
            v-model="ruleForm.emailSubject"
            placeholder="邮件主题"
          ></el-input>
        </el-form-item>

        <el-form-item label="模板变量:">
          <el-select
            v-model="dictValue"
            placeholder="请选择"
            clearable
            class="selWidth"
            @change="selectDict"
          >
            <el-option
              v-for="item in dictData"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="内容:" prop="emailContent">
          <!-- <el-input v-model="ruleForm.emailContent" placeholder="邮件内容"></el-input> -->
          <vue-ueditor-wrap
            v-model="ruleForm.emailContent"
            :config="myConfig"
            @ready="ready"
            @beforeInit="addCustomDialog"
            style="width: 85%; margin-left: 30px"
            @input="handleKeydown"
          ></vue-ueditor-wrap>
        </el-form-item>
        <el-form-item label="简单描述：" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            placeholder="请输入描述"
            type="textarea"
          ></el-input>
        </el-form-item>

        <el-form-item label="模板类型:" prop="emailTemplateType">
          <el-radio-group v-model="ruleForm.emailTemplateType">
            <el-radio :label="1">注册</el-radio>
            <el-radio :label="2">重置密码</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import UserSearchable from "@/components/UserSearchable";

import { getDictData } from "@/api/transaction";

import {
  getEmailtemplate,
  saveEmailtemplate,
  updateEmailtemplate,
  deleteEmailtemplate,
} from "@/api/agent";

import SettingMer from "@/utils/settingMer";
import { getToken } from "@/utils/auth";

export default {
  name: "email",
  components: { UserSearchable },
  data() {
    const url =
      SettingMer.httpUrl + "/upload/image/0/file?ueditor=1&token=" + getToken();
    return {
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: "100%", // 初始容器宽度
        elementPathEnabled: false,
        wordCount: false,
        enableAutoSave: false,
        UEDITOR_HOME_URL: "/UEditor/",
        serverUrl: url,
        imageUrl: url,
        imageFieldName: "file",
        imageUrlPrefix: "",
        imageActionName: "upfile",
        imageMaxSize: 2048000,
        imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
      },
      labelPosition: "right",
      from: {
        // name: '',
        // code: '',
        // keywords: "",
        page: 1,
        limit: 15,
        emailTemplateName: "",
      },
      loading: false,
      tableData: {
        data: [],
        total: 0,
      },
      dialogVisible: false,
      ruleForm: {
        countryId: "",
        emailContent: '<p style="display: inline;"></p>',
        emailSender: "",
        emailSenderAddress: "",
        emailSubject: "",
        emailTemplateName: "",
        emailTemplateNo: "",
        emailTemplateType: "",
        remark: "",
        status: "",
      },
      rules: {
        countryId: [
          {
            required: true,
            message: "请选择国家",
            trigger: "change",
          },
        ],
        emailContent: [
          {
            required: true,
            message: "请输入邮件内容",
            trigger: "blur",
          },
        ],
        emailSender: [
          {
            required: true,
            message: "请输入邮件发件人名称",
            trigger: "blur",
          },
        ],
        emailSenderAddress: [
          {
            required: true,
            message: "请输入邮件发件人地址",
            trigger: "blur",
          },
        ],
        emailSubject: [
          {
            required: true,
            message: "请输入邮件主题",
            trigger: "blur",
          },
        ],
        emailTemplateName: [
          {
            required: true,
            message: "请输入模板名称",
            trigger: "blur",
          },
        ],
        emailTemplateNo: [
          {
            required: true,
            message: "请输入模板编号",
            trigger: "blur",
          },
        ],
        emailTemplateType: [
          {
            required: true,
            message: "请选择模板类型",
            trigger: "change",
          },
        ],
        remark: [
          {
            required: true,
            message: "请输入描述",
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: "请选择状态",
            trigger: "change",
          },
        ],
      },
      countryShow: 1,
      deleteCountrise: [],
      keywords: "",
      dictData: [],
      dictValue: "",
      ueditor: null,
      newdictValue: "",
    };
  },
  mounted() {
    this.getlist();
    this.getDict();
  },
  watch: {
    // 'ruleForm.emailContent': {
    //     handler(newValue, oldValue) {
    //         console.log('变更：', newValue, oldValue);
    //         // 这里可以执行需要的操作
    //     },
    // }
  },
  methods: {
    ready(instance) {
      this.ueditor = instance;
    },
    selectDict(e) {
      let newdictValue =
        '<span style="display:inline">${' + this.dictValue + "}</span>";
      console.log("插入的值：", newdictValue);
      this.ueditor.focus(); // 获取光标位置
      this.ueditor.execCommand("inserthtml", newdictValue);
    },
    handleKeydown(event) {
      console.log(this.ruleForm.emailContent);
      // if (event.includes('${}')) {
      //     console.log('${coding} 触发事件！')
      //     const newValue = event.replace()
      //     console.log(newValue)
      // }
    },
    // 添加自定义弹窗
    addCustomDialog(editorId) {
      window.UE.registerUI(
        "test-dialog",
        function (editor, uiName) {
          // 创建 dialog
          const dialog = new window.UE.ui.Dialog({
            // 指定弹出层中页面的路径，这里只能支持页面，路径参考常见问题 2
            iframeUrl: "/setting/uploadPicture?field=dialog",
            // 需要指定当前的编辑器实例
            editor: editor,
            // 指定 dialog 的名字
            name: uiName,
            // dialog 的标题
            title: "上传图片",
            // 指定 dialog 的外围样式
            cssRules: "width:1000px;height:620px;padding:20px;",
          });
          this.dialog = dialog;
          var btn = new window.UE.ui.Button({
            name: "dialog-button",
            title: "上传图片",
            cssRules: `background-image: url(@/assets/images/icons.png);background-position: -726px -77px;`,
            onclick: function () {
              // 渲染dialog
              dialog.render();
              dialog.open();
            },
          });
          return btn;
        },
        37
      );
    },
    search() {
      this.loading = true;
      console.log(this.from);
      let obj = this.from;
      getEmailtemplate(obj)
        .then((res) => {
          console.log(res);
          this.tableData.data = res.list;
          this.tableData.total = res.total;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    reset() {
      this.from = {
        page: 1,
        limit: 15,
        // keywords: ""
        emailTemplateName: "",
      };
      this.getlist();
    },
    add() {
      this.ruleForm = {
        countryId: "",
        emailContent: "",
        emailSender: "",
        emailSenderAddress: "",
        emailSubject: "",
        emailTemplateName: "",
        emailTemplateNo: "",
        emailTemplateType: "",
        remark: "",
      };
      this.countryShow = 1;
      this.dialogVisible = true;
    },
    handleEdit(row) {
      console.log("编辑", row);

      this.countryShow = 2;

      this.ruleForm = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },

    deleteCountry() {
      let that = this;
      console.log(that.deleteCountrise);

      if (that.deleteCountrise.length < 1) {
        that.$message.warning("请至少选中一个！");
        return;
      }

      let arr = [];
      for (var i = 0; i < that.deleteCountrise.length; i++) {
        arr.push(that.deleteCountrise[i].id);
      }

      console.log(arr);
      // return

      this.$confirm("确认删除？")
        .then((_) => {
          deleteEmailtemplate(arr)
            .then((res) => {
              console.log(res);
              this.$message.success("删除成功");
              this.getlist();
            })
            .catch((err) => {
              console.log(err);
              this.$message.error(err);
            });
        })
        .catch((_) => {});
    },

    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.countryShow != 1) {
            console.log("编辑", this.ruleForm);
            let data = this.ruleForm;

            updateEmailtemplate(data)
              .then((res) => {
                console.log(res);
                this.$message.success("编辑成功");
                this.dialogVisible = false;
                this.getlist();
              })
              .catch((err) => {
                console.log(err);
                this.$message.error(err);
              });
          } else {
            // console.log('新增', this.ruleForm)
            let data = this.ruleForm;
            console.log("新增", data);

            saveEmailtemplate(data)
              .then((res) => {
                // console.log(res)
                this.$message.success("新增成功");
                this.getlist();
                this.dialogVisible = false;
              })
              .catch((err) => {
                console.log(err);
                this.$message.error(err);
              });
          }
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
    getlist() {
      this.loading = true;

      // getCountry(this.from).then(res => {
      //     console.log(res)
      //     this.tableData.data = res.list
      //     this.tableData.total = res.total
      //     this.loading = false
      // }).catch(err => {
      //     console.log(err)
      //     this.loading = false
      // })

      getEmailtemplate(this.from)
        .then((res) => {
          console.log("邮件列表数据：", res);
          this.tableData.data = res.list;
          this.tableData.total = res.total;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    pageChange(page) {
      this.from.page = page;
      this.getlist();
    },
    handleSizeChange(val) {
      this.from.limit = val;
      this.getlist();
    },

    selctTable(selection) {
      let that = this;
      console.log(selection);
      that.deleteCountrise = selection;
    },

    slectTableAll(selection) {
      let that = this;
      console.log(selection);
      that.deleteCountrise = selection;
    },

    // 字典数据
    getDict() {
      getDictData("template_variables")
        .then((res) => {
          console.log("字典变量数据", res);
          this.dictData = res;
        })
        .catch((res) => {
          console.log(res);
        });
    },
  },
};
</script>
<style scoped lang="scss">
.btn_bt {
  border-top: 1px dashed #ccc;
  padding-top: 20px;
}

::v-deep .dialogEmail .el-form-item--medium .el-form-item__label {
  width: 150px !important;
}

::v-deep .dialogEmail .el-form-item__content .el-input--medium {
  width: 85% !important;
}
</style>
